<?php

namespace App\Http\Controllers\admin;
use DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class goodsController extends Controller
{
    public function add()
    {
    	$data = DB::table('sort')
    	     -> select(['id','name','path',DB::raw('concat(path, "," ,id)as str' )])
    	     -> orderBy('str','ASC')
             ->get();
     //dd($data);
        foreach($data as $k => $value)
        {
        	$count = substr_count($value -> path,',');
        	$str = str_repeat('|----',$count);
        	$data[$k] -> name = $str.$value -> name;
        }
    	
 
   

    	return view('admin.goods.add',['data' => $data]);
    }
    //商品添加执行***************************************
    
    public function insert(Request $request)
    {
    	  //dd($request -> all());
    	     $this -> validate($request,[
      	    'img'=>'required',
      	    'price'=>'required',
      	   'name'=>'required',
      	   'content'=>'required',
      	                         ],[
            'img.required'=>'图片不能为空',
            'price.required'=>'价格不能为空',
            'name.required'=>'商品名称不能为空',
            'content.required'=>'商品介绍不能为空',
      	                         ]
      	);
    	  $data = $request -> except('_token');
    	 //上传图片
    	 //判断是否上传
    	 //dd($request -> hasFile('img'));
    	 if($request -> hasFile('img'))

    	 {
    	 	 //判断是否有效
    	 	 if($request -> file('img') -> isValid())
    	 	 {
    	 	 	//获取扩展名称
    	 	 	$suffix = $request -> file('img') -> getClientOriginalExtension();
    	 	 	//随机一个文件名称
    	 	 	$fileName = time().mt_rand(100000,999999).'.'.$suffix;
    	 	 	//移动图片
    	 	 	$request -> file('img') -> move('./uploads',$fileName);
    	 	 	//处理img字段
    	 	 	$data['img'] = '/uploads/'.$fileName;
    	 	 }else{
    	 	 	return back() -> with(['info' => '图片有问题']);
    	 	 }
    	 }else{
    	 	 return back() -> with(['info' => '请上传图片']);
    	 }
         date_default_timezone_set('PRC');
         $data['time'] = date("Y-m-d H:i:s");
        // dd($data);
        //执行添加数据
          $res = DB::table('goods')
            -> insert($data);
            if($res)
            {
            	return redirect('admin/goods/menu') -> with(['info' => '添加成功']);
            }else{
            	return back() -> with(['info' => '添加失败']);
            }
    }
    //列表***************************************************
    public function menu(Request $request)
    {   

      //dd($request -> all);
      $num = $request -> input('num',10);
     	$data = DB::table('goods as c1') 
     	      -> select('c1.*','c2.name as cname')
            -> LeftJoin('sort as c2','c1.sid','=','c2.id')
     	      -> where(function($query)use($request){
     	           	$query->where('c1.name','like','%'.$request->input('keyword').'%');
     	         })
      	    -> paginate($num);
     	  // dd($data);
    
       
    	return view('admin.goods.menu',['data' => $data,'request'=> $request -> all()]);

       	
   }
    //编辑************************************************8
    public function alter($id)
    {	
        //查询当前分类
    	$data = DB::table('goods') -> where('id',$id) -> first();
    	 //查询所有分类
    	$allData = DB::table('sort')
    	     -> select(['id','name','path',DB::raw('concat(path, "," ,id)as str' )])
    	     -> orderBy('str','ASC')
             -> get();
     //dd($data);
        foreach($allData as $k => $value)
        {
        	$count = substr_count($value -> path,',');
        	$str = str_repeat('|----',$count);
        	$allData[$k] -> name = $str.$value -> name;
        }

    	//dd($allData);
    	return view('admin.goods.alter',['data' => $data,'allData' => $allData]);

    }
    //商品编辑执行********************************************
    
    public function update(Request $request)
    {   
    	//dd($request -> all());
        $id = $request -> input('id');
        $oldImg = DB::table('goods') -> where('id',$id) -> first() -> img ;

        //dd($oldImg);
        $data = $request -> except('_token','id','sid');
        //判断是否上传
        if($request -> hasFile('img'))
        {   //判断是否有效
            if($request -> file('img') -> isValid())
            {
                //获取扩展名称
                $suffix = $request -> file('img') ->getClientOriginalExtension();


                //随机一个文件名称
                $fileName = time().mt_rand(100000,999999).'.'.$suffix;


                //移动
                $request -> file('img') ->move('./uploads',$fileName);


                //处理img字段
                $data['img'] = '/uploads/'.$fileName;
                if(file_exists('.'.$oldImg))
                {
                    unlink('.'.$oldImg);
                }
            }
        }
        // dd($data);
        //更新
        $res = DB::table('goods') -> where('id',$id) -> update($data);
        //判断
        if($res)
        {
            return redirect('admin/goods/menu') -> with(['info' => '更新成功']);
        }else{
            return back() -> with(['info' => '更新失败']);
        }
    }
    //商品下架***********************************88
    public function delete($id)
    {

     	$res = DB::table('goods') -> where('id',$id) ->first();
     	//dd($res);
     	$array = [];
     	if($res -> status == 0)
     	{
            $array = ['status' => '1'];
     	}else{
     		$array = ['status' => '0'];
     	}
       $result = DB::table('goods')-> where('id',$id) -> update($array);
       if($result)
       {
       	return redirect('/admin/goods/menu');
       }
     
    }
}

